import React from "react";
const Confirm = () => {
    const [searchParams] = React.Router.useSearchParams()
    const roomid = searchParams.get('roomid') ? searchParams.get('roomid') : 0
    const [info, setInfo] = React.useState<any>({ price: 0 })
    const [dateshow, SetDateshow] = React.useState(false)
    const [guestshow, SetGuestshow] = React.useState(false)
    const [guestlist, SetGuestlist] = React.useState([])
    const [couponshow, SetCouponshow] = React.useState(false)
    const [couponlist, SetCouponlist] = React.useState<any>([])
    const [payshow, SetPayshow] = React.useState(false)
    // 价格
    const [price, SetPrice] = React.useState(0)
    // 原价
    const [originprice, SetOriginprice] = React.useState(0)
    // 天数
    const [day, SetDay] = React.useState(0)
    //支付信息
    const [paylist] = React.useState([[
        { label: '余额支付', value: 'money' },
        { label: '微信支付', value: 'wx' },
        { label: '支付宝支付', value: 'zfb' },
    ]])
    //订单信息
    const [order, setOrder] = React.useState<any>({
        remark: '',
        //日期
        datestr: '',
        starttime: 0,
        endtime: 0,
        //住客
        guest: '',
        gueststr: '请选择住客信息',
        guestids: [],
        //优惠券
        couponid: '',
        couponstr: '',
        //支付方式
        paystr: '余额支付',
        pay: 'money'
    })

    React.useEffect(() => {
        getRoomInfoData();
        getGuestData();
        getCouponData();
    }, [])

    //当订单信息有变化，就重新计算价格
    React.useEffect(() => {
        Total();
    }, [order])

    //计算总价
    const Total = () => {
        let starttime = order.starttime;
        let endtime = order.endtime;

        //时间差
        let day = parseInt(((endtime - starttime) / 86400).toFixed(0));

        //原价 时间差*房间原价
        let truncateDecimals = (num: number) => Math.trunc(num * 100) / 100;
        let origin_price: any = truncateDecimals(parseFloat(info.price) * day);
        let price: any = origin_price;


        //是否有选择优惠券
        if (order.couponid) {
            let rate: any = 1;

            let list = couponlist[0]

            list.map((item: any) => {
                if (item.value == order.couponid) {
                    rate = item.rate
                }
            })

            price = truncateDecimals(parseFloat(rate) * price)
        }

        SetPrice(price)
        SetOriginprice(origin_price)
        SetDay(day)

    }

    const getRoomInfoData = async () => {
        let result = await React.HTTP.post('/room/info', {
            roomid: roomid
        });

        if (result.code == 1) {
            setInfo(result.data)
        }
    }

    const getGuestData = async () => {
        let result = await React.HTTP.post('/guest/guestlist', {
            busid: React.Business.id
        });
        if (result.code == 1) {
            SetGuestlist(result.data)
        }
    }

    const getCouponData = async () => {
        let result = await React.HTTP.post('/coupon/couponlist', {
            busid: React.Business.id
        });
        if (result.code == 1) {

            let data: any = [];
            result.data.map((item: any) => {
                data.push({
                    value: item.id,
                    label: `${item.coupon.title} - ${parseFloat(item.coupon.rate) * 100} 折`,
                    rate: item.coupon.rate
                })
            })
            //给二维数组结构
            SetCouponlist([data])
        }
    }

    // 确认日期
    const DateConfirm = (val: any) => {
        SetDateshow(false);

        // `2025-03-17 - 2025-03-25`
        let datestr = `${new Date(val[0]).toLocaleDateString()} - ${new Date(val[1]).toLocaleDateString()}`

        //获取到开始时间和结束时间
        //标准时间转换为时间戳
        let starttime = Date.parse(new Date(val[0]).toLocaleDateString()) / 1000
        let endtime = Date.parse(new Date(val[1]).toLocaleDateString()) / 1000

        setOrder({
            ...order,
            datestr,
            starttime,
            endtime
        })
    }

    // 住客选择
    const GuestChange = (val: any) => {
        let gueststr: any[] = []
        let guestids: any[] = [];

        guestlist.map((item: any) => {
            if (val.includes(item.id)) {
                gueststr.push(item.nickname)
                guestids.push(item.id)
            }
        })

        var str = gueststr.join('、')
        var ids = guestids.join(',')

        //设置订单数据
        setOrder({
            ...order,
            guest: ids,
            gueststr: str,
            guestids
        })
    }

    // 优惠券
    const CouponChange = (val: any) => {
        SetCouponshow(false)

        if (couponlist.length <= 0) {
            setOrder({
                ...order,
                couponid: '',
                couponstr: '暂无优惠券'
            })

            return false;
        }

        let couponstr = ''

        //获取picker第一项
        let list = couponlist[0]

        list.map((item: any) => {
            if (item.value == val[0]) {
                couponstr = item.label
            }
        })

        setOrder({
            ...order,
            couponid: val[0],
            couponstr
        })
    }

    // 订单备注
    const RemarkChange = (e: any) => {
        setOrder({
            ...order,
            remark: e
        })
    }

    // 确认支付方式 
    const PayChange = (val: any) => {
        SetPayshow(false)

        let paystr = ''

        //获取picker第一项
        let list = paylist[0]

        list.map((item: any) => {
            if (item.value == val[0]) {
                paystr = item.label
            }
        })

        setOrder({
            ...order,
            pay: val[0],
            paystr
        })
    }

    // 确认订单
    const ConfirmOrder = async () => {
        if (day <= 0) {
            React.error('请选择入住日期')
            return false;
        }

        if (order.guestids.length <= 0) {
            React.error('请选择住客')
            return false;
        }

        let data = {
            busid: React.Business.id,
            roomid: roomid,
            guest: order.guest,
            starttime: order.starttime,
            endtime: order.endtime,
            couponid: order.couponid,
            remark: order.remark,
            type: order.pay,
        }

        let result = await React.HTTP.post('/order/add', data);

        if (result.code == 1) {
            React.success(result.msg, () => React.navigate('/order/index'));
        }
        else {
            React.error(result.msg);
        }
    }

    return (
        <>
            <link rel="stylesheet" href="/assets/css/confirm.css" />
            <div className="skeleton">
                <div className="detail">
                    <div className="thumb">
                        <img src={info.thumb_text} alt="" />
                    </div>
                    <div className="right">
                        <p>{info.name}</p>
                        <p>￥{info.price}/晚</p>
                        <div className="tips">
                            {
                                info.flag_text && info.flag_text.map((flag: string, index: number) => {
                                    return (
                                        <span key={index}>{flag}</span>
                                    )
                                })
                            }
                        </div>
                    </div>
                </div>
                <div className="skeleton_rect">
                    {/* 入住日期 */}
                    <div className="item">
                        <label>入住日期</label>
                        <React.UI.Input className="item_right" placeholder='请选择入住日期' value={order.datestr} onClick={() => SetDateshow(true)} />
                    </div>
                    {/* 日期组件 */}
                    <React.UI.CalendarPicker
                        visible={dateshow}
                        selectionMode='range'
                        min={new Date()}
                        onClose={() => SetDateshow(false)}
                        onMaskClick={() => SetDateshow(false)}
                        onConfirm={DateConfirm}
                    />

                    <div className="item">
                        {/* 入住日期 */}
                        <label>住客信息</label>
                        <div className={order.guestids.length > 0 ? 'item_right' : 'item_rights'} onClick={() => { SetGuestshow(true) }}>
                            {order.gueststr}
                        </div>
                    </div>
                    {/* 弹出层组件 */}
                    <React.UI.Popup
                        visible={guestshow}
                        onMaskClick={() => { SetGuestshow(false) }}
                        onClose={() => { SetGuestshow(false) }}
                        destroyOnClose
                    >
                        <div style={{ height: '40vh', overflowY: 'scroll', padding: '20px' }}>
                            <React.UI.CheckList multiple onChange={GuestChange}	>
                                {
                                    guestlist.map((item: any) => {
                                        return (
                                            <React.UI.CheckList.Item value={item.id} key={item.id}>{item.nickname}</React.UI.CheckList.Item>
                                        )
                                    })
                                }
                            </React.UI.CheckList>
                            <React.UI.Button color="primary" block style={{ width: '100%' }} onClick={() => SetGuestshow(false)}>确认</React.UI.Button>
                        </div>
                    </React.UI.Popup>
                </div>
                {/* 优惠券 */}
                <div className="skeleton_price">
                    <div className="tips">优惠券</div>
                    <p>{order.couponstr}</p>
                    <React.UI.Button size="mini" color="primary" onClick={() => SetCouponshow(true)}>选择</React.UI.Button>

                    {/* 优惠券选择器 */}
                    <React.UI.Picker
                        columns={couponlist}
                        visible={couponshow}
                        onClose={() => {
                            SetCouponshow(false)
                        }}
                        onConfirm={CouponChange}
                    />
                </div>

                {/* 支付方式 */}
                <div className="skeleton_price">
                    <div className="tips">支付方式</div>
                    <p>{order.paystr}</p>
                    <React.UI.Button size="mini" color="primary" onClick={() => SetPayshow(true)}>选择</React.UI.Button>

                    {/* 支付方式选择器 */}
                    <React.UI.Picker
                        columns={paylist}
                        visible={payshow}
                        onClose={() => {
                            SetPayshow(false)
                        }}
                        onConfirm={PayChange}
                    />
                </div>

                {/* 订单备注 */}
                <div className="skeleton_rect">
                    <div className="item">
                        <label>订单备注</label>
                        <div className="item_name">
                            <React.UI.TextArea defaultValue={'请输入订单备注'} value={order.remark} showCount maxLength={120} onChange={RemarkChange} />
                        </div>
                    </div>
                </div>

                <div className="skeleton_price">
                    <div className="tips">房间费用</div>
                    <div className="prices">
                        <span>￥{originprice}</span>
                        <span>共 {day} 晚</span>
                    </div>
                </div>
            </div>
            <div className="comfirm_foot_bar">
                {
                    price == originprice ? 
                    <div className="text">
                        <span>总价:</span>
                        <span>￥{price}</span>
                    </div>
                    :
                    <div className="text">
                        <span>总价:</span>
                        <span>￥{price}</span>
                        <s>原价：￥{originprice}</s>
                    </div>
                }

                <React.UI.Button onClick={ConfirmOrder} color='primary' shape='rounded'>提交订单</React.UI.Button>
            </div>
        </>
    )
}

export default Confirm;